<template>
  <div style="width: 100%; min-height: 420px; border: 1px solid var(--w-e-textarea-border-color)">
    <Toolbar
      style="width: 100%; border-bottom: 1px solid var(--w-e-textarea-border-color)"
      :editor="editor"
      :defaultConfig="toolbar_config"
      :mode="mode"
    />
    <Editor
      :style="{ width: '100%', height: height || '336px', minHeight: '336px', overflow: 'auto hidden' }"
      v-model="html"
      :mode="mode"
      :defaultConfig="editor_config"
      @onCreated="onCreated"
      @onChange="onChange"
    />
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { ref, shallowRef, computed, watch, onUnmounted } from 'vue';
import env from '../../env.js';

const isDev = env.get('DEV');
const agentUrl = env.get('VUE_APP_API_BASE_URL');
const uploadUrl = '/fileservice/v1/fileYd';

export default {
  name: 'WangEditor',
  components: { Editor, Toolbar },
  props: {
    height: undefined,
    modelValue: { type: String },
    mode: { type: String, default: 'default' },
    toolbarConfig: { type: Object, default: undefined },
    editorConfig: { type: Object, default: undefined },
  },
  setup(props, { emit }) {
    let html = ref('');
    let editor = shallowRef();
    let toolbar_config = computed(() => {
      return Object.assign({}, props.toolbarConfig);
    });
    let editor_config = computed(() => {
      const config = {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 配置上传图片
          uploadImage: {
            server: isDev ? agentUrl + uploadUrl : uploadUrl, //后端上传地址
            fieldName: 'file',
            //选择文件时的类型限制，默认为['image/*'] 如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],
            metaWithUrl: true, // 参数拼接到 url 上
            meta: { file_path: 'wangEditor' },
            // 上传前
            onBeforeUpload(file) {
              // console.log('onBeforeUpload', file);
              return file.url; // 返回哪些文件可以上传
            },
            // 上传进度的回调函数
            onProgress(progress) {
              // console.log('onProgress', progress);
            },
            // 自定义返回字段
            customInsert(res, insertFn) {
              insertFn(res.data.url, res.data.filename);
            },
            // 单个文件上传成功之后
            onSuccess(file, res) {
              // console.log('onSuccess', file.url, res);
            },
            // 单个文件上传失败
            onFailed(file, res) {
              console.log('onFailed', file, res);
              alert(res.message);
            },
            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
              console.error('onError', file, err, res);
              alert(err.message);
            },
          },
          // 配置上传视频
          uploadVideo: {
            server: isDev ? agentUrl + uploadUrl : uploadUrl, //后端上传地址
            fieldName: 'file',
            metaWithUrl: true, // 参数拼接到 url 上
            meta: { file_path: 'wangEditor' },
            // 上传前
            onBeforeUpload(file) {
              // console.log('onBeforeUpload', file);
              return file.url; // 返回哪些文件可以上传
            },
            // 上传进度的回调函数
            onProgress(progress) {
              // console.log('onProgress', progress);
            },
            // 自定义返回字段
            customInsert(res, insertFn) {
              insertFn(res.data.url, res.data.filename);
            },
            // 单个文件上传成功之后
            onSuccess(file, res) {
              // console.log('onSuccess', file.url, res);
            },
            // 单个文件上传失败
            onFailed(file, res) {
              console.log('onFailed', file, res);
              alert(res.message);
            },
            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
              console.error('onError', file, err, res);
              alert(err.message);
            },
          },
        },
      };
      return Object.assign({}, config, props.editorConfig);
    });

    function onCreated(_editor) {
      editor.value = _editor;
    }
    function onChange() {
      let val = html.value;
      val = val.replace(/<p><br><\/p>/g, '');
      emit('update:modelValue', val ? html.value : '');
    }
    function destroy() {
      if (editor.value) {
        editor.value.destroy();
      }
      props = emit = html = editor = toolbar_config = editor_config = null;
    }

    watch(
      () => props.modelValue,
      (val) => {
        if (html.value !== val) {
          html.value = val;
        }
      },
      { immediate: true }
    );

    onUnmounted(() => {
      destroy();
    });

    return { html, editor, toolbar_config, editor_config, onCreated, onChange };
  },
};
</script>
